package com.tianqu.tms.core.util;
import javax.servlet.ServletException;

import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;

import com.tianqu.tms.core.base.LogManager;
import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.mail.MailHelperManager;
import com.tianqu.tms.core.taglib.MenuBean;
import com.tianqu.tms.core.taglib.MenuDigester;

/**
 * 
 * @author liugang
 *
 */
public class TmsPlugin implements PlugIn {

	/** The {@link ActionServlet} owning this application. */
	private ActionServlet servlet = null;
	
	/** menu配置文件 */
	private String menuConfig = null;
	/** log4j配置文件  */
	private String log4jConfig = null;
	/** mail template 配置文件 */
	private String mailTemplate = null;

	/**
	 * <p>
	 * Log Manager
	 * </p>
	 */
	private Logger logger = Logger.getLogger(TmsPlugin.class);
	
	/**
	 * init
	 */
	public void init(ActionServlet actionServlet, ModuleConfig moduleConfig)
		throws ServletException {

		this.servlet = actionServlet;
		try {
			initLogManager();
			initMenu();
			loadMailTemplate();
			
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}

	/**
	 * 
	 * @throws Exception
	 */
	private void initLogManager() throws Exception {
		LogManager.init(log4jConfig);
	}


	/**
	 * 
	 * @throws Exception
	 */
	private void initMenu() throws Exception {

		if (menuConfig == null) {
			throw new Exception(":Can't get menuConfig");
		}
		try {

			MenuDigester navigationDigester = new MenuDigester();

			MenuBean navigationVO =
				navigationDigester.digest(
					servlet.getServletContext().getRealPath(menuConfig));

			servlet.getServletContext().setAttribute(
				TmsConstants.MENU_VO_KEY,
				navigationVO);

			logger.trace("menu配置文件读取结束"  + menuConfig + navigationVO);

		} catch (Exception e) {
			throw e;

		}
	}
	
	
	/**
	 * 
	 * @throws Exception
	 */
	public void loadMailTemplate() throws Exception{
		if (mailTemplate == null) {
			logger.error( "Can't get mailTemplate" );
			throw new Exception(":Can't get mailTemplate");
		}

		try {
			MailHelperManager.init(servlet.getServletContext().getRealPath(mailTemplate));
		} catch (Exception e) {
			throw e;
		}
	}
	/**
	 * 
	 */
	public void destroy() {
		;
	}
	public void setMenuConfig(String menuConfig) {
		this.menuConfig = menuConfig;
	}

	public void setLog4jConfig(String log4jConfigP) {
		this.log4jConfig = log4jConfigP;
	}

	public String getMailTemplate() {
		return mailTemplate;
	}
	public void setMailTemplate(String mailTemplate) {
		this.mailTemplate = mailTemplate;
	}
}